package com.example.walkera.rkipcamerademo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
//import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

//引入
import com.example.walkera.rkipcamerademo.CameraManager.CameraOpenErrorCallback;


@SuppressLint({
        "NewApi", "ValidFragment"
})
public class MainActivity extends Activity {
    private static final int MENU_EXIT = 0xCC882201;
    private static final String TAG = "MainActivity";

    // NativeAgent nativeAgt;
    CameraView myCamView;
    SurfaceView mSurfaceView;

    boolean inServer = false;
    boolean inStreaming = false;
    static int targetWid = 1920;
    static int targetHei = 1080;

    final String checkingFile = "/mnt/sdcard/ipcam/myvideo.mp4";
    final String resourceDirectory = "/mnt/sdcard/ipcam";
    private ICameraCrashService mService = null;
    private CameraUtil.ServiceToken mToken;
    private Handler mHandler = new Handler();
    private MyBrocastReceiver receiver;
    private AudioManager am;
    private int audio_device = 0;
    private int time_num = 0;
    private boolean isStop=true;

    // memory object for encoder
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //获取音频服务
        am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        Log.e(TAG, "========onCreate===117====================");

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        Window win = getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        win.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                     WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);
        //注册广播
        registerBrocastReceiver();
    }

    //注册广播
    private void registerBrocastReceiver() {
        // TODO Auto-generated method stub
        receiver=new MyBrocastReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction("bestom.hdmiin");
        this.registerReceiver(receiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(receiver);
    }

    @Override
    public void onStart() {
        super.onStart();
        //通过绑定服务
        mToken = CameraUtil.bindToService(this, osc);
        setup();
        isStop = false;
    }

    private ServiceConnection osc = new ServiceConnection() {
        //当服务被绑定成功的时候调用
        public void onServiceConnected(ComponentName classname, IBinder obj) {
            //获取被绑定的服务的IBinder对象,然后通过ibinder对象去指挥后台服务
            mService = ICameraCrashService.Stub.asInterface(obj);
            //这里把服务对象设置给view，同时尝试启动预览功能
            myCamView.setService(mService);
        }

        //当服务被接触绑定的时候调用
        public void onServiceDisconnected(ComponentName classname) {
            mService = null;
        }
    };

    public void onStop() {
        CameraUtil.unbindFromService(mToken);
        super.onStop();
    }

    AudioManager.OnAudioFocusChangeListener afChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        public void onAudioFocusChange(int focusChange) {
            Log.e(TAG, "========onCreate===66==========focusChange==========" + focusChange);
            //mMediaplayerHandler.obtainMessage(FOCUSCHANGE, focusChange, 0).sendToTarget();
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        int result = am.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN);
        if (1 == result){
            audio_device = 1;
        }
        else {
            Toast toast=Toast.makeText(getApplicationContext(), "The sound device being used", Toast.LENGTH_SHORT);
        }
        Log.e(TAG, "========onResume===66==========result==========" + result);
        if (1 == audio_device) {
            Log.e(TAG, "========onResume===66==========audio_device==========" + audio_device);
            mHandler_delay.postDelayed(mRunnable_delay, 1500); // 在Handler中执行子线程并延迟3s。
            //delay(1500);  //延时1.5秒
            //enableHdmiin(true);
        }

    }

    private Runnable mRunnable_delay = new Runnable() {
        @Override
        public void run() {
            mHandler_delay.sendEmptyMessage(1);
        }
    };

    Handler mHandler_delay = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //1.5s后执行代码
            enableHdmiin(true);
            //if (time_num <= 2)
            //{
            mHandler_delay.postDelayed(mRunnable_delay, 2000); // 在Handler中执行子线程并延迟3s。
            //Log.e(TAG, "========onResume===66==========time_num==========" + time_num);
            //time_num ++;
            //}
        }
    };

    @Override
    public void onPause() {
        super.onPause();
        if (1 == audio_device) {
            Log.e(TAG, "========onPause===66==========audio_device==========" + audio_device);
            mHandler_delay.removeCallbacks(mRunnable_delay);
            delay(500);
            enableHdmiin(false);
            delay(1500);  //延时1秒
            am.abandonAudioFocus(afChangeListener);
        }
    }
    private void delay(int ms){
        try {
            Thread.currentThread();
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static boolean enableHdmiin(boolean enable){
        File hdmiFile = new File("/sys/hdmiin/hdmiin_test");
        FileWriter fw = null;
        if(hdmiFile.exists() && hdmiFile.canWrite()){
            try {
                fw = new FileWriter(hdmiFile);
                if(enable)
                    fw.write("1" + "\n");
                else
                    fw.write("2" + "\n");
                fw.flush();

                if(fw != null)
                    fw.close();

            }  catch (IOException e) {
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }

    private void clearResource() {
        String[] str = {
                "rm", "-r", resourceDirectory
        };

        try {
            Process ps = Runtime.getRuntime().exec(str);
            try {
                ps.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setup() {
        clearResource();

        // NativeAgent.LoadLibraries();
        // nativeAgt = new NativeAgent();

        myCamView = (CameraView) findViewById(R.id.surface_overlay);
        mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
        myCamView.SetupCamera(mSurfaceView, mService);

    }


    private void doAction(final boolean isBack) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(getApplicationContext(), R.string.no_storage, Toast.LENGTH_LONG).show();
            return;
        }
        if (mService == null) {
            showToast(MainActivity.this, getString(R.string.msg_prepare_error1));
            return;
        }
        if (isBack){
            try {
                mService.pip(1000,500);
                finish();
            } catch (RemoteException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }
        else{
            boolean ret = false;
            try {
                mService.prepareMedia();
                ret = mService.startRecording();
                if(!ret) {
                    showToast(MainActivity.this, getString(R.string.msg_prepare_error1));
                }
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

    private void showToast(Context context, String message) {
        // create the view
        LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = vi.inflate(R.layout.message_toast, null);

        // set the text in the view
        TextView tv = (TextView) view.findViewById(R.id.message);
        tv.setText(message);

        // show the toast
        Toast toast = new Toast(context);
        toast.setView(view);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.show();
    }

    //广播接收器
    private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            String cmd = intent.getStringExtra("command");
            Log.d(TAG, "mIntentReceiver.onReceive " + action + " / " + cmd);
            if (CameraUtil.START_PREVIEW.equals(action)) {
            }
        }
    };



    private View.OnClickListener low_res_listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            targetWid = 320;
            targetHei = 240;
        }
    };
    private View.OnClickListener medium_res_listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            targetWid = 640;
            targetHei = 480;
        }
    };
    private View.OnClickListener high_res_listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            targetWid = 1280;
            targetHei = 720;
        }
    };



    public CameraOpenErrorCallback getCameraOpenErrorCallback() {
        return mCameraOpenErrorCallback;
    }

    private CameraOpenErrorCallback mCameraOpenErrorCallback = new CameraOpenErrorCallback() {
        @Override
        public void onCameraDisabled(int cameraId) {

            CameraUtil.showErrorAndFinish(MainActivity.this,
                    R.string.camera_disabled);

        }

        @Override
        public void onDeviceOpenFailure(int cameraId) {

            CameraUtil.showErrorAndFinish(MainActivity.this,
                    R.string.cannot_connect_camera);

        }

        @Override
        public void onReconnectionFailure(CameraManager mgr) {

            CameraUtil.showErrorAndFinish(MainActivity.this,
                    R.string.cannot_connect_camera);

        }
    };

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // TODO Auto-generated method stub
        if (KeyEvent.KEYCODE_MENU == event.getKeyCode()) {

        }
        return super.dispatchKeyEvent(event);
    }



    //广播接收器
    class  MyBrocastReceiver extends  BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action=intent.getAction();
            if(action.equals("bestom.hdmiin")){
                try{
                    if(mService!=null){

                        mService.stopRecording();
                        finish();
                    }

                }catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
        }
    }
}
